using Godot;
using System;
using System.Collections.Generic;
using System.Linq;

public partial class AbilityWeightedTable 
{

	public List<PlayerAbility> items = new List<PlayerAbility>();
	int weightSum = 0;

	public struct PlayerAbility{
		public AbilityUpgrade item;
		public int weight;

		public PlayerAbility(AbilityUpgrade item,int weight){
			this.item = item;
			this.weight = weight;
		}
	}

	public void AddItem(AbilityUpgrade ability,int weight){

		items.Add(new PlayerAbility(ability,weight));
		weightSum = weightSum + weight;
	}

	public void RemoveItem(AbilityUpgrade ability){
		items = items.Where(playerAbility=>{
			return playerAbility.item.id != ability.id;
		}).ToList();

		weightSum = 0;
		foreach(PlayerAbility item in items){
			weightSum += item.weight;
		}
	}

	public AbilityUpgrade PickItem(List<AbilityUpgrade> exclude){
		List<PlayerAbility> adjustedItems = items;
		int adjustedWeightSum = weightSum;
		if(exclude.Count > 0){
			adjustedItems = new List<PlayerAbility>();
			adjustedWeightSum = 0;
			foreach(PlayerAbility item in items){
				if( exclude.Contains(item.item)){
					continue;
				}
				adjustedItems.Add(item);
				adjustedWeightSum += item.weight;
			}
		}

		int chosenWeight = GD.RandRange(1,adjustedWeightSum);
		int iterationSum = 0; 
		foreach(PlayerAbility item in adjustedItems){
			iterationSum += item.weight;
			if(chosenWeight <= iterationSum){
				return item.item;
			}
		}
		return null;
	}
}
